﻿/**
 * Created by caelan on 2018/10/25.
 */
var customizeStation = {
  stationName: {
    // AllStation: '所有站',
    CountryStation: '国家站',
    Old723Station: '区域站',
    // TargetStation: '指标站'
    CropStation:'作物类型站',
    RegionStation:'自定义区域'
  },
  /*所有站点*/
  station: [],
  curRegion : null,
  /*当前面板选择的站点*/
  selectStation: [],
  areas:[],
  init: function (areaCode,callback) {
    var _this = this;
    $.ajax({
      // url: '../js/ss.json',
      //后台查询所有站点信息及省市县三级信息
      url: Global.mdrms_service_url+"/mdrms/queryAllBaseStation",
      type: 'post',
      dataType: 'json',
      success: function (res) {
        /*渲染自定义站数据表格面板*/
        _this.renderStation(res.data,areaCode);
        /**根据选择的区域筛选数据 */
        _this.reloadStation();

       /*添加到全局*/
          Global.countryStations = [];
          for(var x=0;x<res.data.allStation.length;x++){
              if(res.data.allStation[x].V01000.substring(0,1)=='5' && res.data.allStation[x].V01000 !="57036" ){
                  Global.countryStations.push( res.data.allStation[x].V01000);
              }else if(res.data.allStation[x].V01000.substring(0,1)=='8'){
                  Global.oldStations.push( res.data.allStation[x].V01000);
              }

          }
          if(callback) callback.call(null,Global.countryStations);//回调

      },
      error: function (e) {
        console.log(e);
      }
    });



    /*站点类型*/
    var stationOption = '';
    for ( var s in _this.stationName ) {
      if ( _this.stationName.hasOwnProperty(s) )
      stationOption += '<option value="'+ s +'">'+ _this.stationName[s] +'</option>';
    }
    $('#customizeStationType').html(stationOption);


    $.ajax({
      url: Global.mdrms_service_url+"/cropStations/queryAllRegion",
      type: 'post',
      dataType: 'json',
      success: function (res) {
        /*渲染自定义站数据表格面板*/
        var d = res.data;
        var options = "<option>全部</option>";
        for(var i=0;i<d.length;i++){
          options += '<option value="'+ d[i].id +'">'+  d[i].name +'</option>';
        }
        $("#regionType").html(options);
        

      },
      error: function (e) {
        console.log(e);
      }
    });


  },
  renderStation: function (response,areaCode) {
    console.log(response);
    var _this = this;
    _this.station = response.allStation;
    $.ajax({
      url: './assets/localData/T_AREA.json',
      type: 'get',
      dataType: 'json',
      success: function (res) {
        if ( res ) {
            /*渲染dom*/
        _this.renderArea(res,areaCode)
        } else {
          console.log();
        }
      
      },
      error: function (e) {
        console.log(e);
      }
    });

    _this.reloadStation();
    layForm.render(null, 'customizeStation');

    /*站点选*/
    layForm.on('select(customizeStationType)', function () { _this.reloadStation(); });
    /*区县选择*/
    layForm.on('select(customizeCounty)', function () { _this.reloadStation(); });
     /*作物类型选择*/
     layForm.on('select(cropType)', function () { _this.reloadStation(); });

     layForm.on('select(regionType)', function (data) { 
      customizeStation.curRegion = data.value;
      $.ajax({
        url: Global.mdrms_service_url+"/cropStations/getRegionStations?subregionid="+data.value,
        type: 'post',
        dataType: 'json',
        success: function (res) {
          /*渲染自定义站数据表格面板*/
          var d = res.data;
          for(var i=0;i<customizeStation.station.length;i++){
              for(var n=0;n<d.length;n++){
                if(customizeStation.station[i].V01000 == d[n].v01000){
                  customizeStation.station[i].region = data.value;
                }
              }
          }

          _this.reloadStation(); 
        
  
        },
        error: function (e) {
          console.log(e);
        }
      });

     });

    /*ui选择事件 市*/
    layForm.on('select(customizeProvince)', function (data) {
         option = '<option data-area="全部" value="全部">全部</option>';//默认选择市的对应第一个区县
         var areacode=data.value;
         var cities = _this.resultData[data.value];
         for( var x = 0; x < _this.resultData.length; x++){
           var vt =_this.resultData[x];
           if(vt.areacode.length == 6 && vt.areacode.substring(0,4)==areacode){
             option += '<option value="'+ vt.areacode +'">'+ vt.areaname +'</option>'
           }
         }
         $("#customizeCounty").html(option);
         layForm.render(null, 'customizeStation');
         $('select[name="customizeCounty"]').next().find('dd:eq(0)').trigger('click');
          _this.reloadStation();
    });

    var toolBar = '<div class="layui-btn-container"> ' +
      '<button style="display: none;" id="getCheckCustomizeStation" lay-event="getCheckData">获取所有选中静态数据</button> ' +
    '</div>';

    layTable.render({
      elem: '#customizeStationTable',				//绑定圆元素
      toolbar: toolBar,					//展示工具栏以及自定义工具元素
      title: '站点信息',			//表名字
      height: 'full-250',				//高度，自适应
      cellMinWidth: 100,				//最小列宽
      skin: 'row', 							//皮肤，无上下边框
      even: true,								//皮肤，开启隔行显示
      cols: [[
        {type:'checkbox'},
        {field: 'V01000', title: '站号'},
        {field: 'CHNAME', title: '站名'},
        {field: 'CHAREAPROVINCE', title: '所属省' },
        {field: 'CHAREACITY', title: '所属市' },
        {field: 'CHAREACOUNTRY', title: '所属区'}
      ]],				//表头
      page: false,								//开启分页
      limit: 3000,
      limits: [3000, 6000, 9000, 3000, 3000],		//分页条数自定义
      data: response.allStation			//数据
    });

    //监听行工具事件
    // layTable.on('toolbar(customizeStationTable)', function(obj){
    //   switch(obj.event){
    //     case 'getCheckData':
    //       if ( _this.selectStation.length < 1 ) {
    //         _this.selectStation = obj.config.data.filter(function(cur) {
    //           return cur.V01000;
    //         });
    //       }
    //     break;
    //   }
    // });

    // selected station dom
    let selectedStation = document.querySelector("#selectedStation"),
        singleSelectStation = selectedStation.querySelector("ul.selectedStation"),
        stationTools = selectedStation.querySelector(".customizeStationTools");

    // single staion selected
    layTable.on('checkbox(customizeStationTable)', function(obj) {
      let checkStatus = layTable.checkStatus("customizeStationTable"),
          selectCheckDatas = checkStatus.data;
  
      if ( obj.checked && obj.type != "all" ) {
        let stationInfo = judgeArrys( _this.selectStation, obj.data.V01000 ),
          singleView = `<li class="singleStation" value="${ obj.data.V01000 }">
                              <p>${ obj.data.CHNAME }</p>
                              <i class="layui-icon layui-icon-close"></i>
                          </li>`;

        if ( stationInfo.status ) {
            _this.selectStation.push( obj.data.V01000 );
            singleSelectStation.insertAdjacentHTML( 'beforeEnd', singleView );
        }
      } else {
          for ( let x = 0; x < selectCheckDatas.length; x++ ) {
            let stationInfo = judgeArrys( _this.selectStation, selectCheckDatas[x].V01000 ),
              singleView = `<li class="singleStation" value="${ selectCheckDatas[x].V01000 }">
                                  <p>${ selectCheckDatas[x].CHNAME }</p>
                                  <i class="layui-icon layui-icon-close"></i>
                              </li>`;

            if ( stationInfo.status ) {
                _this.selectStation.push( selectCheckDatas[x].V01000 );
                singleSelectStation.insertAdjacentHTML( 'beforeEnd', singleView );
            }
          }
      }
    });

    // remove selected single staion
    singleSelectStation.addEventListener( 'click', function(e) {
      let thisDom = e.target;
      if ( thisDom.nodeName == "I" && thisDom.parentNode.nodeName == "LI" ) {
        let stationId = thisDom.parentNode.getAttribute("value"),
          stationInfo = judgeArrys( _this.selectStation, stationId );

        _this.selectStation.splice( stationInfo.index, 1 );
        thisDom.parentNode.remove();
      }
      return false;
    }, false);

    // remove all selected staion
    stationTools.addEventListener( 'click', function(e) {
      let thisDom = e.target;
      if ( thisDom.nodeName == "BUTTON" ) {
        switch( thisDom.getAttribute("name") ) {
          case "removeAllStation":
            _this.selectStation = [];
            singleSelectStation.textContent = "";
          break;
        }
      }
      return false;
    }, false);
    

    function judgeArrys( arrys, value ) {
      let index = 0,
        status = true;
  
      for ( let x = 0; x < arrys.length; x++ ) {
          if ( arrys[x] == value ) {
              index = x;
              status = false;
              break;
          }
      }
  
      return {
        index: index,
        status: status
      };
    }
  },
  /**区域city*/
  //渲染数据
  renderArea: function (res,areaCode) {
    var _this = this;
    _this.resultData =  res.RECORDS;
    var prov = '<option data-area="全部" value="全部">全部</option>';
    var city='<option data-area="全部" value="全部">全部</option>';
    var country='<option data-area="全部" value="全部">全部</option>';
    for ( var x = 0; x <  _this.resultData.length; x++ ) {
      var obj=_this.resultData[x];
      var areacodelen=obj.areacode.length;
   
      if(areacodelen == 2){  //省   
        prov +='<option value="'+ obj.areacode +'">'+  obj.areaname +'</option>';
      }else if(areacodelen==4){ //市
        city += '<option value="'+ obj.areacode +'">'+  obj.areaname +'</option>';
      }else{
        country += '<option value="'+ obj.areacode +'">'+  obj.areaname +'</option>';
      }
    }
    /*添加dom*/
    $("#customizeProvince").html(city);
    $("#customizeCounty").html(country);
    /*ui组件渲染*/
    layForm.render(null, 'customizeStation');
    /*触发省市县选择*/
    if(areaCode.length==4 || areaCode.length==2){
      $("#div_province").css({'pointer-events': "auto"});
      $("#div_Country").css({'pointer-events': "auto"});
       $('select[name="customizeProvince"]').next().find('dd[lay-value="'+areaCode+'"]').trigger('click');
    }else if(areaCode.length==6) {
      var city_areaCode=areaCode.substring(0,4);
      $("#div_province").css({'pointer-events': "none"});
       $('select[name="customizeProvince"]').next().find('dd[lay-value="'+city_areaCode+'"]').trigger('click');
       $('select[name="customizeCounty"]').next().find('dd[lay-value="'+areaCode+'"]').trigger('click');
    }
  },
  /*筛选重载*/
  reloadStation:function () {
    var _this = this;
    var data = _this.station.filter(function (cur) {
      cur.LAY_CHECKED = false;
      var station = $('#customizeStationType').val(),
          province = $('#customizeProvince option:selected').text(),
          county = $('#customizeCounty option:selected').text();
          crop = $('#cropType').val();

          if(station == "RegionStation"){
            $("#div_Region").show();
            $("#div_Crop").hide();
            $("#div_province").hide();
            $("#div_Country").hide();
            if( customizeStation.curRegion != null){
              return cur.region == customizeStation.curRegion;
            }

          } else if(station=='CropStation'){
            $("#div_Crop").show();
            $("#div_province").hide();
            $("#div_Country").hide();
            $("#div_Region").hide();
            province = province === '全部' ? '' : province;
            crop = crop ==='全部' ? '' : crop;
            if(crop==''){
              return (String(cur.STATYPE).indexOf('XIAOMAIStation') > -1 || String(cur.STATYPE).indexOf('YUMIStationStation') > -1
                      || String(cur.STATYPE).indexOf('SHUIDAOStation') > -1 || String(cur.STATYPE).indexOf('CHAYEStation') > -1
                      || String(cur.STATYPE).indexOf('GANJUStation') > -1 || String(cur.STATYPE).indexOf('HETAOStation') > -1
                      || String(cur.STATYPE).indexOf('HONGZAOStation') > -1 || String(cur.STATYPE).indexOf('KIWIStation') > -1
                      || String(cur.STATYPE).indexOf('YINGTAOStation') > -1 || String(cur.STATYPE).indexOf('PINGGUOStation') > -1
                      || String(cur.STATYPE).indexOf('PUTAOStation') > -1
                  );
            }else{
              return String(cur.STATYPE).indexOf(crop) > -1 ;
            }
          }else{
            $("#div_province").show();
            $("#div_Country").show();
            $("#div_Crop").hide();
            $("#div_Region").hide();
            province = province === '全部' ? '' : province;
            county = county === '全部' ? '' : county;
            return String(cur.STATYPE).indexOf(station) > -1 &&
                (String(cur.CHAREACITY).indexOf(province) > -1 || String(province).indexOf(cur.CHAREACITY) > -1 ) &&
                (String(cur.CHAREACOUNTRY).indexOf(county)> -1 || String(county).indexOf(cur.CHAREACOUNTRY) > -1 );
          }

          
          
    });
    layTable.reload('customizeStationTable', {
      data: data,
      page: {
        curr: 1 //重新从第 1 页开始
      }
    });
  }

};